package com.spring.security.config;

import com.spring.security.filter.JWTOncePerRequestFilter;
import com.spring.security.handler.*;
import com.spring.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author HouKunLin
 */
@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Autowired
    private LoginSuccessHandler loginSuccessHandler;

    @Autowired
    private LoginFailureHandler loginFailureHandler;

    @Autowired
    private LogoutSuccessHandler logoutSuccessHandler;

    @Autowired
    private JWTOncePerRequestFilter jwtOncePerRequestFilter;

    @Autowired
    private NotLoginAuthenticationEntryPoint notLoginAuthenticationEntryPoint;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http
                .exceptionHandling()
                .authenticationEntryPoint(notLoginAuthenticationEntryPoint)
                .and()
                .authorizeRequests()
                .antMatchers("/", "/test/**", "/user/principal5")
                .permitAll()
                .anyRequest()
                .authenticated()
                // .accessDecisionManager()
                /*.withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O fsi) {
                        fsi.setSecurityMetadataSource(mySecurityMetadataSource());
                        fsi.setAccessDecisionManager(myAccessDecisionManager());
                        return fsi;
                    }
                })*/
                .and()
                .logout()
                .logoutUrl("/login/logout")
                .logoutSuccessHandler(logoutSuccessHandler)
                .permitAll()
                .and()
                .formLogin()
                .successHandler(loginSuccessHandler)
                .failureHandler(loginFailureHandler)
                .loginProcessingUrl("/login/login")
                .permitAll()
        ;
        // ExpressionUrlAuthorizationConfigurer url = http.getConfigurer(ExpressionUrlAuthorizationConfigurer.class);
        http.addFilterAt(jwtOncePerRequestFilter, UsernamePasswordAuthenticationFilter.class);


       /* UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();

        // EmailPasswordAuthenticationFilter emailFilter = new EmailPasswordAuthenticationFilter();
        filter.setAuthenticationManager(authenticationManager());
        filter.setAuthenticationSuccessHandler(loginSuccessHandler);
        filter.setAuthenticationFailureHandler(loginFailureHandler);

        http.addFilterAt(filter, UsernamePasswordAuthenticationFilter.class);*/
    }

    @Bean
    public DaoAuthenticationProvider daoAuthenticationProvider() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(userService);
        daoAuthenticationProvider.setUserDetailsPasswordService(userService);
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
        // hideNotFound异常信息设置为false，不隐藏该信息
        daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
        return daoAuthenticationProvider;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
        auth.
                authenticationProvider(daoAuthenticationProvider())
        // .userDetailsService(userService)
        // .passwordEncoder(passwordEncoder())
        // .userDetailsPasswordManager(userService)

        ;

    }

    @Bean(BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public FilterInvocationSecurityMetadataSource mySecurityMetadataSource() {
        return new MyFilterInvocationSecurityMetadataSource();
    }

    @Bean
    public AccessDecisionManager myAccessDecisionManager() {
        return new MyAccessDecisionManager();
    }
}
